//
//  MyKeyboard.h
//  SnakeGame
//
// refered http://stackoverflow.com/a/448982
//

#include "MyKeyboard.h"

#include <stdio.h>
#include <unistd.h>
#include <sys/select.h>
#include <termios.h>

struct termios orig_termios;

void SetKeyRawMode(void)
{
    struct termios new_termios;
    
    // store orig_termios
    tcgetattr(fileno(stdin), &orig_termios);
    
    //copy to new_termios
    memcpy(&new_termios, &orig_termios, sizeof(struct termios));
    
    // register cleanup handler and set the new terminal mode
    atexit(RecoverKeyMode);
    cfmakeraw(&new_termios);
    tcsetattr(fileno(stdin), TCSANOW, &new_termios);
}

void RecoverKeyMode(void)
{
    tcsetattr(fileno(stdin), TCSANOW, &orig_termios);
}

int MyKBHit(void)
{
    struct timeval tv = { 0L, 0L };
    fd_set fds;
    FD_ZERO(&fds);
    FD_SET(fileno(stdin), &fds);
    
    return select(1, &fds, NULL, NULL, &tv);
}

int MyGetCh(void)
{
    int ret = 0;
    char c = '\0';
    
    if((ret = read(fileno(stdin), &c, sizeof(char))) < 0)
    {
        return ret;
    }
    
    return c;
}